/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package models;
import java.util.*;
import javax.persistence.*;
import play.data.format.*;
import play.data.validation.*;
import play.db.jpa.*;

@Entity
public class Usuario {

    @Id
    @Constraints.Required
    public String login;
    @Constraints.Required
    public String password;
    @Constraints.Required
    public String nombreCompleto;
    @Transient
    public Boolean esAdministrador;
    public Integer administrador;
    public Integer estado;
    
    @Formats.DateTime(pattern="yyyy-MM-dd")
    public Date fechaCreacion;
    
    public static Usuario findById(String login) {
        return JPA.em().find(Usuario.class, login);
    }
    
    public void update(String login) {
        this.login = login;
        JPA.em().merge(this);
    }
    
    public void save() {
        System.out.println("Grabando nuevo usuario...");
        this.estado = new Integer(1);
        JPA.em().persist(this);
    }
    public void delete() {
        JPA.em().remove(this);
    }
    
    public static Page page(int page, int pageSize, String sortBy, String order, String filter) {
        if(page < 1) page = 1;

        @SuppressWarnings("unchecked")
				List<Usuario> data = JPA.em()
            .createQuery("from Usuario u where lower(u.login) like ? order by u." + sortBy + " " + order)
            .setParameter(1, "%" + filter.toLowerCase() + "%")
            .setFirstResult((page - 1) * pageSize)
            .setMaxResults(pageSize)
            .getResultList();
        
        Long total=Long.parseLong(data.size()+"");
        return new Page(data, total, page, pageSize);
    }
    
     public static class Page {
        
        private final int pageSize;
        private final long totalRowCount;
        private final int pageIndex;
        private final List<Usuario> list;
        
        public Page(List<Usuario> data, long total, int page, int pageSize) {
            this.list = data;
            this.totalRowCount = total;
            this.pageIndex = page;
            this.pageSize = pageSize;
        }
        
        public long getTotalRowCount() {
            return totalRowCount;
        }
        
        public int getPageIndex() {
            return pageIndex;
        }
        
        public List<Usuario> getList() {
            return list;
        }
        
        public boolean hasPrev() {
            return pageIndex > 1;
        }
        
        public boolean hasNext() {
            return (totalRowCount/pageSize) >= pageIndex;
        }
        
        public String getDisplayXtoYofZ() {
            int start = ((pageIndex - 1) * pageSize + 1);
            int end = start + Math.min(pageSize, list.size()) - 1;
            return start + " al " + end + " de " + totalRowCount;
        }
        
    }
}
